package org.jerrymouse.agentContainer;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.jerrymouse.jsa4j.db.kv.DB;
import org.jerrymouse.jsa4j.db.kv.DBManagerFactory;

public class AgentContainer {

	private static Map<Class<? extends Agent>, Agent> map = new HashMap<Class<? extends Agent>, Agent>();
	static DB db;

	/**
	 * 可以强制转型
	 * 
	 * @param type
	 * @return
	 */
	public Agent create(Class<? extends Agent> type) {
		Agent agent = null;
		try {
			agent = type.getConstructor().newInstance();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		if (agent != null) {
			agent.setAgentContainer(this);
			agent.db = db;
		}
		return agent;
	}

	public Agent get(Class<? extends Agent> type) {
		Agent agent = map.get(type);
		if (agent == null)
			agent = create(type);
		return agent;
	}
}
